<template>
    <div id="stream" style="height: 93vh;" class="flex-1 py-5 sm:px-6 lg:px-5 flex flex-col ml-64">
        <div class="flex-1 bg-white shadow-md rounded-lg p-4 overflow-y-auto" ref="chatArea">
            <!-- 聊天消息区域 -->
            <div class="flex flex-col space-y-4">
                <div v-for="(message, index) in chatMessages" :key="index"
                    :class="{ 'flex justify-start': !message.isUser, 'flex justify-end': message.isUser }">
                    <div :class="{ 'bg-gray-200': !message.isUser, 'bg-blue-100': message.isUser }"
                        class="p-3 rounded-lg max-w-xl">
                        <!--展示消息内容-->
                        <div v-html="processContent(message.content)"></div>
                    </div>
                </div>
            </div>
        </div>
        <!-- 输入框和发送按钮 -->
        <div class="mt-4 flex space-x-4">
            <input v-model="inputMessage" type="text" placeholder="输入你的问题..."
                class="flex-1 border border-gray-300 rounded-md p-3 focus:outline-none focus:border-blue-500"
                @keydown.enter="sendMessage">
            <button @click="sendMessage"
                class="bg-blue-500 text-white px-4 py-3 rounded-md hover:bg-blue-600 focus:outline-none">
                发送
            </button>
        </div>
    </div>
</template>

<script setup>
import { useAdminInfoStore } from '../../../store';
import { ref, onMounted, watch } from 'vue'
import axios from "axios";
import MarkdownIt from 'markdown-it';
const isLoading = ref(false);
const md = new MarkdownIt();
// 聊天区域绑定
const chatArea = ref()
// 实例化容器
const adminInfo = useAdminInfoStore();
// 输入框
const inputMessage = ref('');
// 消息列表
const chatMessages = adminInfo.getChatMessages;
const url = import.meta.env.VITE_API_BASE_URL + '/chat/streamCall';
// 自动滚动到结尾
onMounted(() => {
    // 移除 setInterval，改用手动滚动
    watch(chatMessages, () => scrollToBottom(), { deep: true })
})

// 滚动
const scrollToBottom = () => {
    if (chatArea.value) {
        chatArea.value.scrollTop = chatArea.value.scrollHeight
    }
}

// 处理内容
const processContent = (content) => {
    // 替换 <ref>[num]</ref> 为 <sup>[num]</sup>
    let newContent = content.replace(/<ref>\[(\d+)\]<\/ref>/g, '【$1】');
    newContent = md.render(newContent);
    return newContent;
};


// 发送消息
const sendMessage = () => {
    // 防止空白输入
    if (inputMessage.value.trim() === '') return;
    // 添加用户消息
    chatMessages.push({ content: inputMessage.value, isUser: true, docRefs: [] });
    // 添加回答消息
    chatMessages.push({ content: '正在加载中···', isUser: false, docRefs: [] });
    scrollToBottom();
    axios.post(
        url,
        inputMessage.value,
        {
            headers: {
                token: adminInfo.getToken,
                'Content-Type': 'text/plain'
            },
            onDownloadProgress: (e) => {
                if (!isLoading.value) {
                    isLoading.value = true;
                    chatMessages[chatMessages.length - 1].content = '';
                }
                const fullText = e.event.target.responseText // 累积的完整文本
                let newText = fullText.substring(chatMessages[chatMessages.length - 1].content.length)
                chatMessages[chatMessages.length - 1].content += newText //增量更新
                scrollToBottom() // 实时滚动
            },
        }
    ).catch(error => {
        console.error(error);
        chatMessages[chatMessages.length - 1] = {
            content: '请求出错，请稍后重试。',
            isUser: false,
            docRefs: []
        };
    }).finally(() => {
        isLoading.value = false;
    })
    // 清空输入框
    inputMessage.value = '';
}
</script>

<style scoped></style>